var express = require('express');
var router = express.Router();
const subInfoModel = require('./../model/subInfoModel')
const subUserModel = require("./../model/subUserModel");

router.get('/list',async function(req,res,next){
    let page = parseInt(req.query.page, 10);
    let pageSize = parseInt(req.query.pageSize,10);
    let {subName,subMoney,subRAM,subType} = req.query
    if(isNaN(page) || isNaN(pageSize) || page < 1 || pageSize < 1){
        return res.status(400).send({
            code: 400,
            message: '查询参数不正确'
        });
    }
    const skipValue = (page - 1) * pageSize;
    let query = {};
    if (subName) query.subName = new RegExp(subName, 'i'); // 'i' 代表忽略大小写
    if (subMoney) query.subMoney = Number(subMoney)
    if (subRAM) query.subRAM = new RegExp(subRAM, 'i');
    if (subRAM) query.subRAM = subRAM

    try{
        const results = await subInfoModel.aggregate([
            { $match: query },
            { $facet: {
                    "totalData": [{ $skip: skipValue }, { $limit: pageSize }],
                    "totalCount": [{ $count: "count" }]
                }}
        ]);
        const data = results[0].totalData;
        const total = results[0].totalCount[0] ? results[0].totalCount[0].count : 0;

        res.status(200).send({
            code: 0,
            data: data,
            total: total,
            currentPage:page,
            pageSize:pageSize,
            message: '查询成功'
        })
    }catch(err){
        next(err);
    }

})

router.post('/addSubInfo',async function(req,res,next){
    let {subName,subMoney,subDes,subRAM,subType} = req.body
    try{
        let existingresult = await subInfoModel.findOne({ subName: subName });
        if(existingresult){
            // 如果已存在，返回错误信息
            return res.status(200).send({ // 409 Conflict 代表请求存在冲突，如数据已存在
                code: 409,
                message: '当前名称已存在!'
            });
        }
        await subInfoModel.create({
            subName,subMoney,subDes,subRAM,subType,
            createTime:new Date(),
        })
        res.status(200).send({
            code:0,
            message:'添加成功'
        })
    }catch(err){
        next(err)
    }
})

router.post('/editSubInfo',function(req,res,next){
   let {subName,subMoney,subDes,_id,subRAM,subType} = req.body
    subInfoModel.updateOne(
        { "_id": _id },
        { $set: { subName,subMoney,subDes,subRAM,subType,updateTime:new Date() }}
    ).then(data=>{
         res.status(200).send({
             code:0,
             message:'修改成功'
         })
    }).catch(err=>{
        next(err)
    })
})

router.post('/delSubInfo',function(req,res,next){
    let {_id} = req.body
    subInfoModel.deleteOne(
        { "_id": _id }, // 查询条件
    ).then(data=>{
        res.status(200).send({
            code:0,
            message:'修改成功'
        })
    }).catch(err=>{
        next(err)
    })
})

module.exports = router;
